#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildCommandTrackerForm():
    Dict={}
    Dict['Station']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['Distance']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    return Dict



def ProcessCommandTrackerForm(form):
    try:
        Stationid=form.data['Station']
        station=Station.objects.filter(id=Stationid)[0]
    except:
        station=None
    try:
        Distance=float(form.data['Distance'])
    except:
        Distance=1000 * djangoproject.settings.COOPGISDistanceMultiplier
    Results=[]
    if(not station):
        return Results
    
    Commands1=Command.objects.filter(StartPoint__distance_lte=(station.Point, Distance))
    Commands2=Command.objects.filter(EndPoint__distance_lte=(station.Point, Distance))
    Commands=[]
    for i in Commands1:
        Commands.append(i)
    for i in Commands2:
        if(not i in Commands):
            Commands.append(i)

    for command in Commands:
        Row=[]
        if(command.StartPoint):
            Row.append(str(int(command.StartPoint.distance(station.Point))))
        elif(command.EndPoint):
            Row.append(str(int(command.EndPoint.distance(station.Point))))
        Row.append(str(command.id))
        if(command.Name in ['EditAssembly', 'DeleteAssembly']):
            Row.append(str(command.Get('Assemblyid')))
        else:
            Row.append('')
        TempStation=''
        if(command.StartPoint):
            TempStation=Station.objects.filter(Point__distance_lte=(command.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))
        if(command.EndPoint):
            TempStation=Station.objects.filter(Point__distance_lte=(command.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))
        if(TempStation):
            TempStation=str(TempStation[0].id)
        Row.append(TempStation)
        Row.append(str(command.CommandUserName))
        Row.append(str(command.Name))
        Row.append(str(command.AssemblyName))
        Row.append(str(command.CommandCreateDateTime))
        Results.append(Row)
    Results.sort(lambda row1, row2: int(row1[0]) - int(row2[0]))
    Heading=[['Distance', 'Commandid', 'Assemblyid', 'Stationid', 'User Name', 'Command Name', 'Assembly', 'Date']]
    
    return Heading + Results


